import {
  createSlice,
  createAsyncThunk,
  type PayloadAction,
} from "@reduxjs/toolkit";

function sleep(time = 1000) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("");
    }, time);
  });
}

/**
 * 通过 createAsyncThunk 创建异步动作
 *
 * 参数：
 *    typePrefix: 动作类型前缀
 *
 *    payloadCreatore: payload 创建函数
 *      内部可以编写异步代码，需要有返回值，返回值就是一个 payload
 *
 * 返回值
 *    actionCreator
 */

export const hello = createAsyncThunk("hello", async () => {
  await sleep();

  throw new Error("我错了");
});

console.log("hello", hello());

let nextId = 2;

const slice = createSlice({
  name: "task",

  initialState: {
    raws: [{ id: 1, text: "吃饭", done: false }],
  },

  reducers: {
    add(state, { payload }: PayloadAction<string>) {
      state.raws.push({
        id: nextId++,
        text: payload,
        done: false,
      });

      // return {
      //   ...state,
      //   raws: [
      //     ...state.raws,
      //     {
      //       id: nextId++,
      //       text: payload,
      //       done: false,
      //     },
      //   ],
      // };
    },
  },

  extraReducers: (builder) => {
    // 监听 hello 动作派发之后，fulfilled 的情况
    builder.addCase(hello.fulfilled, (state, action) => {
      console.log("hello fulfilled", action);
    });

    // 监听 hello 动作派发之后，pending 的情况
    builder.addCase(hello.pending, () => {
      console.log("hello pending");
    });

    // 监听 hello 动作派发之后，rejected 的情况
    builder.addCase(hello.rejected, () => {
      console.log("hello rejected");
    });
  },
});

export const { add } = slice.actions;

export default slice.reducer;
